import { interopDefault } from 'mlly'
import Dysmsapi20170525, { SendSmsRequest} from '@alicloud/dysmsapi20170525';

import  {Config} from '@alicloud/openapi-client';
import {RuntimeOptions} from '@alicloud/tea-util';

const smsConfig = useAppConfig().alisms;
const Dysmsapi= interopDefault(Dysmsapi20170525);
class Client {

  static createClient(): Dysmsapi {
    let config = new Config({
      accessKeyId: smsConfig.accessKeyId,
      accessKeySecret: smsConfig.accessKeySecret,
    });
    config.endpoint = `dysmsapi.aliyuncs.com`;

    return new Dysmsapi(config);
  }

  static async main(phone:string,code:string): Promise<void> {
    let client = Client.createClient();
    let sendSmsRequest = new SendSmsRequest({
      phoneNumbers: phone,
      signName: smsConfig.signName,
      templateCode: smsConfig.templateCode,
      templateParam: `{"code":${code}}`,
    });
    let runtime = new RuntimeOptions({ });
    try {
      await client.sendSmsWithOptions(sendSmsRequest, runtime);
    } catch (error) {
      console.log(error.message);
      console.log(error.data["Recommend"]);
      
    }    
  }

}


export default eventHandler(async (event) => {
  const { phone,code } = await readBody(event);
  const response = await Client.main(phone,code);
  return response;
})
